<template>
  <div class="user-management-container">
    <el-card>
      <div slot="header" class="card-header">
        <h2>用户管理</h2>
      </div>

      <!-- 查询条件区域 -->
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="80px" class="query-form">
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="queryParams.mobile" placeholder="请输入手机号" clearable style="width: 200px"></el-input>
        </el-form-item>

        <el-form-item label="姓名" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入姓名" clearable style="width: 200px"></el-input>
        </el-form-item>

        <el-form-item label="性别" prop="sex">
          <el-select v-model="queryParams.sex" placeholder="请选择性别" clearable style="width: 200px">
            <el-option label="男" value="1"></el-option>
            <el-option label="女" value="0"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="出生日期">
          <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" value-format="YYYY-MM-DD" style="width: 300px"></el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 用户列表 -->
      <div class="card-header">
        <el-button type="primary" @click="handleAdd">
          <el-icon>
            <Plus />
          </el-icon>
          新增
        </el-button>
        <el-button type="success" @click="handleExport">
          <el-icon>
            <Download />
          </el-icon>
           导出
        </el-button>

      </div>

      <el-table v-loading="loading" :data="userList" border style="width: 100%; margin-top: 20px"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50rem"></el-table-column>
        <el-table-column prop="id" label="ID" min-width="100rem"></el-table-column>
        <el-table-column prop="name" label="姓名"></el-table-column>
        <el-table-column prop="mobile" label="手机号"></el-table-column>
        <el-table-column prop="sex" label="性别">
          <template #default="scope">
            {{ scope.row.sex === 1 ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column prop="birthDate" label="出生日期"></el-table-column>
        <el-table-column prop="createTime" label="注册时间" min-width="89px"></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" link>编辑</el-button>
            <el-button size="small" link text-color="#ff4d4f">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页控件 -->
      <div class="pagination-container" v-if="total > 0">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="pagination.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="total" size="small"></el-pagination>
      </div>
    </el-card>

    <!-- 新增用户弹窗 -->
    <el-dialog title="新增用户" v-model="dialogVisible" width="50%" :close-on-click-modal="false">
      <el-form ref="userFormRef" :model="userForm" label-width="100px" :rules="rules">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="userForm.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="userForm.mobile" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="userForm.sex" placeholder="请选择性别">
            <el-option label="男" value="1"></el-option>
            <el-option label="女" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="出生日期" prop="birthDate">
          <el-date-picker v-model="userForm.birthDate" type="date" placeholder="请选择出生日期"
            value-format="YYYY-MM-DD"></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import { getPageList, save } from '@/api/userManage';
import { Download, Plus } from '@element-plus/icons-vue';
import axios from 'axios';


// 新增用户相关
const dialogVisible = ref(false);
const userFormRef = ref(null);
const userForm = reactive({
  name: '',
  mobile: '',
  sex: '',
  birthDate: ''
});

// 表单验证规则
const rules = reactive({
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  sex: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  birthDate: [
    { required: true, message: '请选择出生日期', trigger: 'change' }
  ]
});

// 打开新增弹窗
const handleAdd = () => {
  // 重置表单
  userFormRef.value && userFormRef.value.resetFields();
  // 清空表单数据
  Object.keys(userForm).forEach(key => {
    userForm[key] = '';
  });
  // 显示弹窗
  dialogVisible.value = true;
};

// 提交新增表单
const handleSubmit = async () => {
  // 表单验证
  await userFormRef.value.validate();

  // 调用后端新增接口
  const response = await save(userForm);
  dialogVisible.value = false;
  // 重新获取列表数据
  getUserList();
};


// 查询参数
const queryParams = reactive({
  mobile: '',
  name: '',
  sex: '',
  dateStart: '',
  dateEnd: ''
});

// 日期范围
const dateRange = ref([]);

// 表格数据
const userList = ref([]);
const total = ref(0);
const loading = ref(false);
const queryFormRef = ref(null);
const multipleSelection = ref([]);

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10
});

// 监听日期范围变化
watch(dateRange, (newVal) => {
  if (newVal && newVal.length === 2) {
    queryParams.dateStart = newVal[0];
    queryParams.dateEnd = newVal[1];
  } else {
    queryParams.dateStart = '';
    queryParams.dateEnd = '';
  }
});

// 获取用户列表数据
const getUserList = async () => {
  try {
    loading.value = true;

    // 构造请求参数
    const params = {
      ...queryParams,
      page: pagination.currentPage,
      pageSize: pagination.pageSize
    };

    // 调用后端接口
    const data = await getPageList(params);
    userList.value = data.records;
    total.value = data.total;

    // // 假设后端返回格式为 { code: 200, data: { records: [], total: 0 }, msg: '' }
    // if (response.data.code === 200) {
    //   userList.value = response.data.data.records;
    //   total.value = response.data.data.total;
    // } else {
    //   ElMessage.error(response.data.msg || '获取用户列表失败');
    // }
  } finally {
    loading.value = false;
  }
};

// 处理查询
const handleQuery = () => {
  pagination.currentPage = 1; // 重置为第一页
  getUserList();
};

// 处理重置
const handleReset = () => {
  queryFormRef.value.resetFields();
  dateRange.value = [];
  pagination.currentPage = 1;
  getUserList();
};

// 处理页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  getUserList();
};

// 处理页码变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page;
  getUserList();
};

// 处理选择变化
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

// 处理导出功能
const handleExport = async () => {
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '正在导出数据，请稍候...',
    background: 'rgba(0, 0, 0, 0.7)'
  });

  try {
    // 构造导出参数（使用当前查询条件）
    const params = { ...queryParams };
    
    // 调用导出接口，指定responseType为blob
    const response = await axios({
      method: 'get',
      url: '/admin/user/export',
      params: params,
      responseType: 'blob' // 重要：指定响应类型为blob
    });
    
    // 处理返回的blob数据
    const blob = new Blob([response.data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' // Excel MIME类型
    });
    
    // 获取文件名（从响应头中获取）
    let fileName = '用户列表.xlsx';
    const contentDisposition = response.headers['content-disposition'];
    if (contentDisposition) {
      try {
        // 解码文件名
        fileName = decodeURIComponent(contentDisposition.split('filename=')[1]);
      } catch (e) {
        console.warn('解析文件名失败，使用默认文件名');
      }
    }
    
    // 创建下载链接并触发下载
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = fileName;
    document.body.appendChild(a);
    a.click();
    
    // 清理
    window.URL.revokeObjectURL(url);
    document.body.removeChild(a);
    
    ElMessage.success('数据导出成功');
  } catch (error) {
    console.error('导出数据出错:', error);
    ElMessage.error('数据导出失败，请稍后重试');
  } finally {
    // 关闭加载提示
    loadingInstance.close();
  }
};

// 页面加载时获取数据
onMounted(() => {
  getUserList();
});
</script>

<style scoped>
.user-management-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  margin-left: 48rem;
  text-align: right;
}

.query-form {
  margin-bottom: 10px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}
</style>
